import logging
import ConfigParser
import string

class ConfigManager:
	_configFile = None
	_parser = None

	sqliteDbaseFile = None
	importPath = None
	logFile = None
	logLevel = None
	projectName = None
	lighttpdSocket = None

	def __init__(self, configFile = None):
		self._configFile = configFile
		self._parser = ConfigParser.SafeConfigParser()
		if self._configFile is not None:
			self.load()

	def configFile(self, configFile = None):
		if configFile is None:
			return self._configFile
		self._configFile = configFile
		return self._configFile
		
	def get(self, section, key):
		try:
			with open(self._configFile, "r") as fp:
				self._parser.readfp(fp)
				data = string.strip(self._parser.get(section, key))
				logging.debug("Data fetched from config: '{}'".format(data))
				return data
		except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) as e:
			return None
		#	if required:
		#		logging.critical("Error parsing config file: {}".format(e))
		#		pass
		#	return None
		except IOError as e:
			logging.critical("Error opening config file: {}".format(e))
			raise 
		except:
			logging.critical("Unexpected error: {}".format(sys.exc_info()[0]))
			raise

	def load(self):
		self.sqliteDbaseFile = self.get("pdrive", "dbase")
		self.importPath = self.get("pdrive", "importpath")
		self.logFile = self.get("pdrive", "logFile")
		self.logLevel = self.get("pdrive", "logLevel")
		self.projectName = self.get("pdrive", "projectname")
		self.lighttpdSocket = self.get("pdrive", "lighttpdSocket")
		return True
